// 数据统计仪表板组件
import { Statistic, Carousel } from 'antd';
import { ArrowUpOutlined } from '@ant-design/icons';
import React, { useRef, useEffect, useState } from 'react';
import { useModel } from 'umi';
import * as echarts from 'echarts';
import orderform from '@/images/img9065418c9f9a51a0.png';
import today from '@/images/img9067518c9f9f7220.png';
import comment from '@/images/img9068718c9fa15e50.png';
import compare from '@/images/img9069318c9fa215e8.png';
import first from '@/images/fgdgdsfgdfg.png';
import second from '@/images/fdgdgfdb.png';
import rank from '@/images/fgfdgdfg.png';
import { useStatisticsApi } from '@/api/index/index';
import styles from './index.module.css';

// 类型定义 

/**
 * 统计数据接口
 */
interface StatsData {
  TotalMoney: {
    label: string[];      // 收益统计标签
    value: number[];     // 收益统计数值
  };
  order: Array<{         // 订单统计数据
    name: string;        // 订单类型名称
    value: number[];     // 订单数值
    itemStyle: { color: string }; // 订单颜色样式
  }>;
  order_totalMoney: number; // 订单总收益
  person: Array<{        // 人员占比数据
    name: string;        // 人员类型名称
    value: number[];     // 人员数值
    itemStyle: { color: string }; // 人员颜色样式
  }>;
  tide: {               // 趋势数据
    xAxis: string[];     // X轴数据（日期）
    goods: number[];     // 商品数量
    score: number[];    // 订单评分
  };
  today_newOrder: number;   // 今日新增订单
  today_newRemark: number;  // 今日新增评论
  remark_yesterday: number; // 较昨日新增
  rankingImage: string[];    // 排名图片
  squad_ranking: any[];     // 班级排名
  student_ranking: any[];   // 学生排名
  teacher: string[];       // 教师图片
}

/**
 * 排名项接口
 */
interface RankItem {
  ranking: number;       // 排名序号
  name: string;          // 名称
  avatar: string;        // 头像URL
  score: number;         // 积分
}

/**
 * 统计卡片数据接口
 */
interface StatCard {
  title: string;         // 标题
  value: number;         // 数值
  icon: string;          // 图标
  precision?: number;     // 数值精度
  suffix: string | React.ReactNode; // 后缀
}

/**
 * 数据统计主组件
 */
const DataStatisticsDashboard: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const statisticsApi = useStatisticsApi();
  
  // 状态管理
  const [loading, setLoading] = useState(false);              // 加载状态
  const [responseData, setResponseData] = useState<StatsData>(); // 统计数据

  // 图表DOM引用
  const lineChartRef = useRef<HTMLDivElement>(null);      // 折线图容器
  const pieChartRef = useRef<HTMLDivElement>(null);       // 人员占比饼图容器
  const orderPieChartRef = useRef<HTMLDivElement>(null); // 订单统计饼图容器
  const columnChartRef = useRef<HTMLDivElement>(null);   // 柱状图容器

  // 图表实例引用
  const chartsRef = useRef<echarts.ECharts[]>([]);        // 图表实例数组

  // 图表初始化函数

  /**
   * 初始化订单统计饼图
   * @returns 图表实例
   */
  const initOrderPieChart = (): echarts.ECharts | undefined => {
    if (!orderPieChartRef.current || !responseData?.order) return;

    // 销毁之前的图表实例
    const existingChart = echarts.getInstanceByDom(orderPieChartRef.current);
    if (existingChart) {
      existingChart.dispose();
      chartsRef.current = chartsRef.current.filter(ch => ch !== existingChart);
    }

    // 初始化图表实例
    const chart = echarts.init(orderPieChartRef.current);
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}',
        textStyle: { fontSize: 9 }
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        bottom: '5%',
        textStyle: { fontSize: 8 }
      },
      series: [{
        name: '订单统计',
        type: 'pie',
        radius: ['45%', '65%'],
        center: ['50%', '40%'],
        data: responseData.order.map(item => ({
          value: item.value?.[0] || 0,
          name: item.name,
          itemStyle: item.itemStyle
        })),
        label: {
          formatter: '{b}',
          fontSize: 10
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    });

    // 添加到图表实例数组
    chartsRef.current.push(chart);
    return chart;
  };

  /**
   * 初始化人员占比饼图
   * @returns 图表实例
   */
  const initPersonPieChart = (): echarts.ECharts | undefined => {
    if (!pieChartRef.current || !responseData?.person) return;

    // 销毁之前的图表实例
    const existingChart = echarts.getInstanceByDom(pieChartRef.current);
    if (existingChart) {
      existingChart.dispose();
      chartsRef.current = chartsRef.current.filter(ch => ch !== existingChart);
    }

    // 初始化图表实例
    const chart = echarts.init(pieChartRef.current);
    chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}',
        textStyle: { fontSize: 10 }
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        bottom: '5%',
        itemGap: 12,
        itemWidth: 8,
        itemHeight: 8,
        textStyle: { fontSize: 10 }
      },
      series: [{
        name: '人员占比',
        type: 'pie',
        radius: '65%',
        center: ['50%', '40%'],
        data: responseData.person.map(item => ({
          value: item.value?.[0] || 0,
          name: item.name,
          itemStyle: item.itemStyle
        })),
        label: {
          show: true,
          formatter: '{b}: {d}%',
          fontSize: 10
        },
        labelLine: {
          show: true,
          length: 8,
          length2: 4,
          lineStyle: { width: 0.8 }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    });

    chartsRef.current.push(chart);
    return chart;
  };

  /**
   * 初始化收益统计柱状图
   * @returns 图表实例
   */
  const initRevenueColumnChart = (): echarts.ECharts | undefined => {
    if (!columnChartRef.current || !responseData?.TotalMoney) return;
    
    // 销毁之前的图表实例
    const existingChart = echarts.getInstanceByDom(columnChartRef.current);
    if (existingChart) {
      existingChart.dispose();
      chartsRef.current = chartsRef.current.filter(ch => ch !== existingChart);
    }

    // 初始化图表实例
    const chart = echarts.init(columnChartRef.current);
    const { label = [], value = [] } = responseData.TotalMoney;
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        textStyle: { fontSize: 10 },
        padding: 6,
        formatter: (params: any) => {
          const data = params[0];
          return `${data.name}<br/>收益: ${data.value}元`;
        }
      },
      legend: { show: false },
      grid: {
        left: '10%',
        right: '10%',
        bottom: '10%',
        top: '10%',
        containLabel: true
      },
      xAxis: [{
        type: 'value',
        axisTick: { show: false },
        axisLabel: { fontSize: 10 },
      }],
      yAxis: [{
        type: 'category',
        data: label,
        axisTick: { show: false },
        axisLine: { show: false },
        axisLabel: { fontSize: 10, color: '#666' }
      }],
      series: [{
        name: '收益',
        type: 'bar',
        data: value,
        itemStyle: {
          color: '#5470C6',
        },
        label: {
          show: false,
          position: 'left',
          fontSize: 10,
          color: '#666',
          formatter: '{c}元'
        }
      }]
    };

    chart.setOption(option);
    chartsRef.current.push(chart);
    return chart;
  };

  /**
   * 初始化本月订单趋势折线图
   * @returns 图表实例
   */
  const initMonthlyTrendLineChart = (): echarts.ECharts | undefined => {
    if (!lineChartRef.current || !responseData?.tide) return;

    // 销毁之前的图表实例
    const existingChart = echarts.getInstanceByDom(lineChartRef.current);
    if (existingChart) {
      existingChart.dispose();
      chartsRef.current = chartsRef.current.filter(ch => ch !== existingChart);
    }

    // 初始化图表实例
    const chart = echarts.init(lineChartRef.current);
    const { xAxis = [], goods = [], score = [] } = responseData.tide;
    chart.setOption({
      tooltip: {
        trigger: 'axis',
        textStyle: { fontSize: 10 },
        padding: 6
      },
      grid: {
        left: '5%',
        right: '3%',
        bottom: '8%',
        top: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xAxis,
        axisTick: { alignWithLabel: true, lineStyle: { width: 0.8 } },
        axisLine: { lineStyle: { width: 0.8 } },
        axisLabel: { fontSize: 10, rotate: 15 }
      },
      yAxis: {
        type: 'value',
        axisTick: { lineStyle: { width: 0.8 } },
        axisLine: { lineStyle: { width: 0.8 } },
        axisLabel: { fontSize: 10 },
        splitLine: { lineStyle: { width: 0.8, opacity: 0.6 } }
      },
      series: [
        {
          name: '商品数量',
          type: 'line',
          data: goods,
          symbolSize: 4,
          lineStyle: { width: 1.5 },
          itemStyle: { color: '#5470c6' }
        },
        {
          name: '订单评分',
          type: 'line',
          data: score,
          symbolSize: 4,
          lineStyle: { width: 1.5 },
          itemStyle: { color: '#91cc75' }
        }
      ]
    });

    chartsRef.current.push(chart);
    return chart;
  };

  /**
   * 渲染排名列表
   * @param rankingData 排名数据
   * @param isClassRanking 是否为班级排名
   * @returns 排名列表组件
   */
  const renderRankingList = (rankingData: RankItem[], isClassRanking: boolean = false) => {
    if (!rankingData || rankingData.length === 0) {
      return <div className={styles.noData}>暂无数据</div>;
    }
    
    return (
      <div className={styles.rankingTable}>
        <table className={styles.rankTable}>
          <thead>
            <tr>
              <th>排名</th>
              <th>{isClassRanking ? '班级名称' : '学生姓名'}</th>
              <th>积分</th>
            </tr>
          </thead>
          <tbody>
            {rankingData.map((item, index) => {
              // 渲染排名图标
              let rankContent;
              if (item.ranking === 1) {
                rankContent = <img src={first} alt="第一名" className={styles.rankIcon} />;
              } else if (item.ranking === 2) {
                rankContent = <img src={second} alt="第二名" className={styles.rankIcon} />;
              } else if (item.ranking === 3) {
                rankContent = <img src={rank} alt="第三名" className={styles.rankIcon} />;
              } else {
                rankContent = <span className={styles.rankNumber}>{item.ranking}</span>;
              }
              
              return (
                <tr key={index}>
                  <td className={styles.rankCell}>{rankContent}</td>
                  <td>
                    <div className={styles.nameCell}>
                      {!isClassRanking && item.avatar && (
                        <div className={styles.avatarColumn}>
                          <img src={item.avatar} alt={`${item.name}的头像`} className={styles.studentAvatar} />
                        </div>
                      )}
                      <span className={styles.studentName}>{item.name}</span>
                    </div>
                  </td>
                  <td className={styles.scoreCell}>{item.score}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  };

  // 顶部统计卡片数据
  const statCards: StatCard[] = [
    {
      title: '订单总收益',
      value: responseData?.order_totalMoney || 0,
      icon: orderform,
      precision: 2,
      suffix: '¥',
    },
    {
      title: '今日新增订单',
      value: responseData?.today_newOrder || 0,
      icon: today,
      suffix: '个',
    },
    {
      title: '今日新增评论',
      value: responseData?.today_newRemark || 0,
      icon: comment,
      suffix: '个',
    },
    {
      title: '较昨日新增',
      value: responseData?.remark_yesterday || 0,
      icon: compare,
      suffix: (
        <span className={styles.percentDown}>
          % <ArrowUpOutlined />
        </span>
      ),
    },
  ];

  // 数据获取
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await statisticsApi.signIn({});
        setResponseData(response.data || {});
      } catch (error) {
        console.error('接口请求失败：', error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // 图表初始化和 resize 逻辑
  useEffect(() => {
    if (!responseData) return;

    /**
     * 初始化所有图表
     */
    const initAllCharts = () => {
      // 检查所有图表容器是否已挂载
      const chartConfigs = [
        { ref: lineChartRef, initFn: initMonthlyTrendLineChart, name: '月度趋势图' },
        { ref: pieChartRef, initFn: initPersonPieChart, name: '人员占比图' },
        { ref: orderPieChartRef, initFn: initOrderPieChart, name: '订单统计图' },
        { ref: columnChartRef, initFn: initRevenueColumnChart, name: '收益统计图' }
      ];

      const allReady = chartConfigs.every(config => config.ref.current !== null);

      if (allReady) {
        try {
          // 初始化所有图表
          chartConfigs.forEach(config => {
            config.initFn();
          });
        } catch (error) {
          console.error('图表初始化失败:', error);
        }
      } else {
        // 如果容器未准备好，延迟重试
        setTimeout(initAllCharts, 50);
      }
    };
    
    // 延迟初始化以确保DOM已渲染
    const initTimer = setTimeout(initAllCharts, 100);
    return () => {
      clearTimeout(initTimer);
    };
  }, [responseData]);

  // 图表 resize 处理
  useEffect(() => {
    /**
     * 处理窗口大小变化
     */
    const handleResize = () => {
      chartsRef.current.forEach(chart => {
        try {
          chart.resize();
        } catch (error) {
          console.error('图表resize失败:', error);
        }
      });
    };

    // 添加 resize 事件监听器
    window.addEventListener('resize', handleResize);
    
    return () => {
      // 清理事件监听器
      window.removeEventListener('resize', handleResize);
      
      // 组件卸载时清理所有图表实例
      chartsRef.current.forEach(chart => {
        try {
          chart.dispose();
        } catch (error) {
          console.error('图表销毁失败:', error);
        }
      });
      chartsRef.current = [];
    };
  }, []);

  // 数据处理

  /**
   * 处理学生排名数据
   */
  const studentRankingData: RankItem[] = responseData?.student_ranking?.map((item: any, index: number) => ({
    ranking: index + 1,
    name: item.name || '未知学生',
    avatar: item.avatar || '',
    score: item.score || 0
  })) || [
    { ranking: 0, name: '暂无数据', avatar: '', score: 0 },
  ];

  /**
   * 处理班级排名数据
   */
  const classRankingData: RankItem[] = responseData?.squad_ranking?.map((item: any, index: number) => ({
    ranking: index + 1,
    name: item.title || '未知班级',
    avatar: item.avatar || '',
    score: item.score || 0
  })) || [
    { ranking: 0, name: '暂无数据', avatar: '', score: 0 },
  ];

  return (
    <div className={styles.container}>
      {/* 顶部统计卡片区域 */}
      <div className={styles.statsContainer}>
        {statCards.map((stat, index) => (
          <div key={index} className={styles.statItem}>
            <img src={stat.icon} alt={stat.title} className={styles.icon} />
            <div className={styles.textContainer}>
              <div className={styles.title}>{stat.title}</div>
              <Statistic 
                value={stat.value} 
                precision={stat.precision} 
                suffix={stat.suffix} 
                className={styles.value} 
              />
            </div>
            {index !== statCards.length - 1 && <div className={styles.divider} />}
          </div>
        ))}
      </div>

      {/* 图表展示区域 */}
      <div className={styles.chartContainer}>
        {/* 订单统计饼图 */}
        <div className={styles.chartData}>
          <span className={styles.chartTitle}>订单统计</span>
          <div className={styles.chartContent} ref={orderPieChartRef} />
        </div>
        
        {/* 人员占比饼图 */}
        <div className={styles.chartData}>
          <span className={styles.chartTitle}>人员占比</span>
          <div className={styles.chartContent} ref={pieChartRef} />
        </div>
        
        {/* 收益统计柱状图 */}
        <div className={styles.chartData}>
          <span className={styles.chartTitle}>收益统计</span>
          <div className={styles.chartContent} ref={columnChartRef} />
        </div>
      </div>

      {/* 排名展示区域 */}
      <div className={styles.statistics}>
        {/* 学生积分排名 */}
        <div className={styles.exhibition}>
          <div className={styles.showData}>
            <span className={styles.demonstrate}>学生积分排名</span>
            <p>查看更多</p>
          </div>
          <div className={styles.rankingContent}>
            {renderRankingList(studentRankingData, false)}
          </div>
        </div>

        {/* 班级积分排名 */}
        <div className={styles.exhibition}>
          <div className={styles.showData}>
            <span className={styles.demonstrate}>班级积分排名</span>
            <p>查看更多</p>
          </div>
          <div className={styles.rankingContent}>
            {renderRankingList(classRankingData, true)}
          </div>
        </div>

        {/* 优秀教师展示轮播图 */}
        <div className={styles.exhibition}>
          <div className={styles.showData}>
            <span className={styles.demonstrate}>优秀教师展示</span>
            <p>查看更多</p>
          </div>
          <div className={styles.teacherCarousel}>
            <Carousel autoplay autoplaySpeed={3000} arrows={false}>
              {responseData?.teacher?.map((imgUrl, index) => (
                <div key={index} className={styles.carouselItem}>
                  <img
                    src={imgUrl}
                    alt={`优秀教师${index + 1}`}
                    className={styles.teacherImage}
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = 'https://via.placeholder.com/200?text=暂无图片';
                    }}
                  />
                </div>
              ))}
            </Carousel>
          </div>
        </div>
      </div>

      {/* 月度趋势图表区域 */}
      <div className={styles.chartContainer}>
        <div className={styles.chartData}>
          <span className={styles.chartTitle}>本月订单趋势</span>
          <div className={styles.chartContent} ref={lineChartRef} />
        </div>
      </div>
    </div>
  );
};

export default DataStatisticsDashboard;